import yaml
from utils.file_dir import yaml_dir, get_model_template_dir, get_testdata_dir
import re
import json
from pathlib import Path


# yaml_data = read_yaml_data('get_index.yaml')


def read_yaml_all(yaml_path):
    try:
        # 打开文件
        with open(yaml_dir(yaml_path), "r", encoding="utf-8") as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
            return data
    except:
        return None


# 定义一个函数来替换占位符
def replace_placeholders(s, variables):
    # 处理 {user_id} 格式的占位符
    pattern = re.compile(r'\{([^}]+)\}')
    matches = pattern.findall(s)
    for match in matches:
        if match in variables:
            s = s.replace(f'{{{match}}}', variables[match])
    # 处理 {{ token }} 格式的占位符
    pattern = re.compile(r'\{\{(.+?)\}\}')
    matches = pattern.findall(s)
    for match in matches:
        if match.strip() in variables:
            s = s.replace(f'{{{{{match.strip()}}}}}', variables[match.strip()])
    return s

# 遍历字典并替换占位符
def process_data(data, variables):
    if isinstance(data, dict):
        for key in data:
            if isinstance(data[key], str):
                data[key] = replace_placeholders(data[key], variables)
            else:
                process_data(data[key], variables)
    elif isinstance(data, list):
        for i in range(len(data)):
            if isinstance(data[i], str):
                data[i] = replace_placeholders(data[i], variables)
            else:
                process_data(data[i], variables)
    return data


def read_template_yaml_all(file_path):
    try:
        # 打开文件
        with open(get_model_template_dir(file_path), "r", encoding="utf-8") as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
            return data
    except:
        return None


def save_test_cases(test_cases, filename):
    if str(filename).endswith(".yaml"):
        try:
            # 获取输出目录并创建（核心修复点）
            output_dir = Path(get_testdata_dir())
            output_dir.mkdir(parents=True, exist_ok=True)  # 确保根目录存在

            # 构建完整文件路径（包含子目录）
            file_path = output_dir / filename

            # 新增：创建父目录（处理多级路径）
            file_path.parent.mkdir(parents=True, exist_ok=True)  # <--- 关键修复

            # 数据序列化与保存
            yaml_output = yaml.dump(
                test_cases,
                allow_unicode=True,
                sort_keys=False,
                indent=2,
                default_flow_style=False
            )
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(yaml_output)

            print(f"成功生成 {len(test_cases)} 个测试用例")
            print(f"YAML文件已保存至: {file_path.resolve()}")

        except Exception as e:
            raise Exception(f"保存测试用例异常: {e}")


